package com.manage.servlet;







import com.manage.pojo.ResultData;
import com.manage.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        //获取methodName属性(标记不同请求操作)
        String methodName = req.getParameter("methodName");
        if(methodName == null || methodName.isEmpty()){
            //提示请求接口错误
            ResultData resultData = new ResultData(10000,"请求接口格式有误");
            String json = JsonUtils.objectToString(resultData);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(json);
            return;
        }
        //1、获取类对象(a、对象.getClass()   b、类名.class   c、Class.forName("全限定名") )
        Class<?> c = this.getClass();
        //2、根据方法名称获取Method对象
        try {
            Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //3、反射调用方法
            //invoke的返回值就是调用方法的返回值。如果调用的那个方法没有返回值，invoke方法调用的返回值就是null
            Object returnData = method.invoke(c.newInstance(), req, resp);
            if(returnData != null){
                String json = JsonUtils.objectToString(returnData);
                resp.setContentType("application/json;charset=utf-8");
                resp.getWriter().write(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);

    }
}